import pygame, sys
from pygame.locals import *
import random

class Bird():
    def __init__(self):
        pygame.init()
        self.playSurface = pygame.display.set_mode((640, 480))     
        pygame.display.set_caption("别碰到柱子")                    
        self.blackColor = pygame.Color(0, 0, 0)                  
        self.whiteColor = pygame.Color(255, 255, 255)               
        self.purpleColor = pygame.Color(255, 0, 255)                 
        self.greenColor = pygame.Color(0,255,0)                 
        self.birdSegments = [20,230]
        self.direction = "right"
        self.score = 0 
        self.speed = 20
        self.upblocklist = [[120,0],[300,0],[500,0]]
        self.uplength = [160,180,200]
        self.downblocklist = [[120,250],[300,260],[500,300]]
        # 过下一关
        self.next = False
        self.life = 1
        # 设计定时器
        self.MYEVENT01 =pygame.USEREVENT + 1
        pygame.time.set_timer(self.MYEVENT01,1000)
        self.finaltime = 10
        self.fpsclock = pygame.time.Clock()   

    def drawBird(self):
        self.birdrect = pygame.Rect(self.birdSegments[0],self.birdSegments[1],20,20)
        pygame.draw.rect(self.playSurface,self.purpleColor,self.birdrect)

    def drawRect(self):
        # 设计一个保存障碍物的rect数组
        self.blockRects = []
        if self.next:
            self.newx1 = random.randint(120,140)
            self.newx2 = random.randint(240,320)
            self.newx3 = random.randint(450,520)
            self.upblocklist = [[self.newx1,0],[self.newx2,0],[self.newx3,0]]
            self.uplength = [random.randint(160,230),random.randint(200,235),random.randint(200,260)]
            self.downblocklist = [[self.newx1,270],[self.newx2,260],[self.newx3,300]]
            self.greenColor = pygame.Color(random.randint(0,255),random.randint(0,255),random.randint(100,255))
            self.next = False
            self.speed += 5

        for i in self.upblocklist:
            self.ubl = pygame.Rect(i[0],i[1],20,self.uplength[self.upblocklist.index(i)])
            self.blockRects.append(self.ubl)
            pygame.draw.rect(self.playSurface,self.greenColor,self.ubl)
        
        for i in self.downblocklist:
            self.dbl = pygame.Rect(i[0],i[1],20,240)
            self.blockRects.append(self.dbl)
            pygame.draw.rect(self.playSurface,self.greenColor,self.dbl)
    def isalive(self):
        # 出界直接死亡
        if self.birdSegments[1] not in range(0,620):
            self.life = 0
        else:    
            self.upblocklistxlist = [i[0] for i in self.upblocklist]
            
            if self.birdSegments[0]==self.upblocklistxlist[0]:
                if not (pygame.Rect.colliderect(self.birdrect,self.blockRects[0]) or pygame.Rect.colliderect(self.birdrect,self.blockRects[3])):
                    self.score += 1
                else:
                    self.life = 0
            # 2
            if self.birdSegments[0]==self.upblocklistxlist[1]:
                if not (pygame.Rect.colliderect(self.birdrect,self.blockRects[1]) or pygame.Rect.colliderect(self.birdrect,self.blockRects[4])):
                    self.score += 1
                else:
                    self.life = 0
            # 3
            if self.birdSegments[0]==self.upblocklistxlist[2]:
                if not (pygame.Rect.colliderect(self.birdrect,self.blockRects[2]) or pygame.Rect.colliderect(self.birdrect,self.blockRects[5])):
                    self.score += 1
                else:
                    self.life = 0
            
        

    def move(self):
        self.birdSegments[0] += 2
        if self.direction == "up":
            self.birdSegments[1] -= 2
        if self.direction == "down":
            self.birdSegments[1] += 2
        # 判断出界
        if self.birdSegments[0] >= 640:
            self.birdSegments[0] = 0
            self.next = True
        

    def main(self):
        """主程序"""
        while True:
            #
            while self.life:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:       
                        pygame.quit()
                        sys.exit()
                    if event.type == KEYDOWN:
                        if event.key == K_DOWN:
                            self.direction = "down"
                        if event.key == K_UP:
                            self.direction = "up"
                    if event.type == self.MYEVENT01:
                        self.finaltime -= 1
                        if not self.finaltime:
                            pygame.time.set_timer(self.MYEVENT01,0)
                        
                        
                if self.finaltime:
                    self.playSurface.fill([255,200,0])
                    self.font = pygame.font.SysFont('simsunnsimsun',50)
                    self.gameTitle=self.font.render("别碰到柱子",True,[0,0,255])
                    self.font = pygame.font.SysFont('simsunnsimsun',25)
                    self.gameInfo1=self.font.render("玩法介绍：↑：向上移动   ↓：向下移动",True,[0,0,255])
                    self.gameInfo2=self.font.render("碰到柱子以及四周游戏结束",True,[0,0,255])
                    self.timeInfo=self.font.render("倒计时: %d"%self.finaltime,True,[255,0,0])

                    self.playSurface.blit(self.gameTitle,[200,50])
                    self.playSurface.blit(self.gameInfo1,[80,150])
                    self.playSurface.blit(self.gameInfo2,[80,250])
                    self.playSurface.blit(self.timeInfo,[240,350])

                else:
                    self.playSurface.fill(self.blackColor)
                    self.drawRect()
                    self.isalive()
                    #
                    if self.life==0:
                        break
                    self.move()
                    self.drawBird()
                    self.scorecontent=self.font.render("Score: %d"%self.score,True,[255,205,0])
                    self.playSurface.blit(self.scorecontent,[10,20])
                self.fpsclock.tick(self.speed) 
                pygame.display.update() 

            while not self.life:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:       
                        pygame.quit()
                        sys.exit()
                    # 如果点击继续游戏，那么重新开始
                    # 如果点击退出游戏，那么就直接退出
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        x,y = pygame.mouse.get_pos()
                        if self.btn1[0]+self.btn1[2] > x > self.btn1[0]:
                            if self.btn1[1]+self.btn1[3] > y > self.btn1[1]:
                                self.continuegame()
                        if self.btn2[0]+self.btn2[2] > x > self.btn2[0]:
                            if self.btn2[1]+self.btn2[3] > y > self.btn2[1]:
                                self.exit()
            
                self.playSurface.fill([255,200,0])
                self.font = pygame.font.SysFont('simsunnsimsun',80) # simsunnsimsun 宋体
                self.warning=self.font.render("游戏结束",True,[0,0,255])
                self.scorecontent=self.font.render("分数: %d"%self.score,True,[0,0,255])
                self.playSurface.blit(self.warning,[160,50]) 
                self.playSurface.blit(self.scorecontent,[160,200])
                self.addbutton()
                pygame.display.update()  
    def addbutton(self):
        self.btn1 = self.button("继续",340,320,150,80,[0,0,0],self.continuegame)
        self.btn2 = self.button("退出",150,320,150,80,[0,0,0],self.exit)
    def exit(self):
        pygame.quit()
        sys.exit()
    def continuegame(self):
        self.life = 1
        self.birdSegments = [20,230]
        self.score = 0
        self.direction = "right"
        self.font = pygame.font.SysFont('simsunnsimsun',25)
        self.main()
        
    # 添加退出或者重新游戏按钮
    def button (self,msg, x, y, w, h, color, action):
        pygame.draw.rect(self.playSurface, [90,157,158], (x,y,w,h))
        self.font = pygame.font.SysFont('simsunnsimsun',50) # simsunnsimsun 宋体
        textSurf=self.font.render(msg,True,color)
        textRect = textSurf.get_rect()
        textRect.center = ((x+(w/2)), (y+(h/2)))
        self.playSurface.blit(textSurf, textRect)
        return textRect

if __name__ == "__main__":
    game = Bird()
    game.main()

